﻿#include "ClosableListWidgetItem.h"
#include <QApplication>
#include <QStyle>
#include <QHBoxLayout>

ClosableListWidgetItem::ClosableListWidgetItem(QWidget *parent)
    : QWidget(parent)
    , m_labelIcon(new QLabel(this))
    , m_labelText(new QLabel(this))
    , m_btnClose(new QPushButton(this))
    , m_contextMenu(new FMenu(this))
{
    QHBoxLayout* layout = new QHBoxLayout(this);
    // 设置布局
    layout->setContentsMargins(5, 2, 5, 2);
    layout->setSpacing(5);

    // 配置图标标签
    m_labelIcon->setFixedSize(16, 16);
    // m_labelIcon->setPixmap(QApplication::style()->standardIcon(QStyle::SP_TitleBarCloseButton).pixmap(m_labelIcon->size()));
    // setIcon(QApplication::style()->standardIcon(QStyle::SP_MessageBoxWarning));

    // 配置文本标签
    m_labelText->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);

    // 配置关闭按钮
    m_btnClose->setFixedSize(16, 16);
    m_btnClose->setIcon(QApplication::style()->standardIcon(QStyle::SP_TitleBarCloseButton));
    m_btnClose->setFlat(true);
    m_btnClose->setCursor(Qt::PointingHandCursor);
    m_btnClose->setToolTip(tr("Remove from list"));
    m_btnClose->setVisible(false); // 默认隐藏

    // 添加到布局
    layout->addWidget(m_labelIcon);
    layout->addWidget(m_labelText);
    layout->addWidget(m_btnClose);

    setLayout(layout);

    // 连接信号
    connect(m_btnClose, &QPushButton::clicked, this, &ClosableListWidgetItem::closeRequested);

    setMouseTracking(true);
}

void ClosableListWidgetItem::setIcon(const QIcon &icon)
{
    m_labelIcon->setPixmap(icon.pixmap(m_labelIcon->size()));
}

QIcon ClosableListWidgetItem::icon() const
{
    return QIcon(*(m_labelIcon->pixmap()));
}

void ClosableListWidgetItem::setText(const QString &text)
{
    m_labelText->setText(text);
}

QString ClosableListWidgetItem::text() const
{
    return m_labelText->text();
}

FMenu* ClosableListWidgetItem::contextMenu() const
{
    return m_contextMenu;
}


void ClosableListWidgetItem::contextMenuEvent(QContextMenuEvent *event)
{
    if (!m_contextMenu) return;
    m_contextMenu->exec(event->globalPos());
}

void ClosableListWidgetItem::showCloseButton(bool show)
{
    m_btnClose->setVisible(show);
}

void ClosableListWidgetItem::enterEvent(QEvent *event)
{
    QWidget::enterEvent(event);
    showCloseButton(true);
}

void ClosableListWidgetItem::leaveEvent(QEvent *event)
{
    QWidget::leaveEvent(event);
    showCloseButton(false);
}

bool ClosableListWidgetItem::eventFilter(QObject *watched, QEvent *event)
{
    // 处理关闭按钮上的鼠标事件，防止事件冒泡到父部件
    if (watched == m_btnClose) {
        if (event->type() == QEvent::Enter || event->type() == QEvent::Leave) {
            return true; // 阻止事件传播
        }
    }
    return QWidget::eventFilter(watched, event);
}
